﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using KBManagement.DAL;
using KBManagement.Library;

namespace KBManagement
{
    public partial class WareHouse : Form,InforObserver,LoginObserver
    {
        KBSQLClassDataContext context;
        int grvStoreTempIndex = 0;
        int dgvWareHouseIndex = 0;
        IQueryable wareHouse;
        IQueryable wareHouseExport;
        IQueryable storeTempQuery;
        IQueryable wareHouseQuery;
        Admin admin;

        public WareHouse()
        {
            Utils.CreateInstance().AddInforObserver(this);
            Utils.CreateInstance().AddAdminObserver(this);
            context = new KBSQLClassDataContext(); ;
            InitializeComponent();
            SelectWareHouse("all");
            SelectStoreLog(true);
            SelectStoreLog(false);
            SelectStoreTemp("all");
        }

        private void SelectWareHouse(string mode)
        {
            context = new KBSQLClassDataContext();

            switch (mode)
            {
               
                case "thieu":
                    wareHouseQuery = from fc in context.Stores where fc.Quantity < fc.QuantityStandard select fc;
                    break;
                case "du":
                    wareHouseQuery = from fc in context.Stores where fc.Quantity >= fc.QuantityStandard select fc;
                    break;
                default:
                    wareHouseQuery = from fc in context.Stores select fc;
                    break;
            }
            dgvWareHouse.DataSource = wareHouseQuery;
            dgvWareHouse.Columns[0].HeaderText = "Mã số";
            dgvWareHouse.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dgvWareHouse.Columns[1].HeaderText = "Tên sản phẩm";
            dgvWareHouse.Columns[2].HeaderText = "Số lượng";
            dgvWareHouse.Columns[3].HeaderText = "Cảnh báo";
            dgvWareHouse.Columns[4].HeaderText = "Đơn vị";
            dgvWareHouse.Columns[5].HeaderText = "Số lượng tiêu chuẩn";
            nhậpNhàngToolStripMenuItem.Enabled = false;
            xuấtHàngToolStripMenuItem.Enabled = false;
            toolStripButton1.Enabled = false;
            toolStripButton2.Enabled = false;
            try
            {
                dgvWareHouse.CurrentCell = dgvWareHouse[0, dgvWareHouseIndex];
            }
            catch (Exception)
            {
            }
        }

        private void SelectStoreTemp(string mode)
        {

            context = new KBSQLClassDataContext();
            IQueryable storeTemp;
            switch (mode)
            { 
                case "thieu":
                    storeTemp = from fc in context.StoreTemps where fc.Quantity<=0
                                select new
                                {
                                    fc.Store.ID,
                                    fc.Store.S_Name,
                                    fc.Quantity,
                                    fc.Warning,
                                    fc.Store.Unit
                                };
                    storeTempQuery = from fc in context.StoreTemps where fc.Quantity<=0 select fc;
                break;
                case "du":
                storeTemp = from fc in context.StoreTemps where fc.Quantity>0
                            select new
                            {
                                fc.Store.ID,
                                fc.Store.S_Name,
                                fc.Quantity,
                                fc.Warning,
                                fc.Store.Unit
                            };
                storeTempQuery = from fc in context.StoreTemps where fc.Quantity > 0 select fc;
                break;
                default :
                storeTemp = from fc in context.StoreTemps
                            select new
                            {
                                fc.Store.ID,
                                fc.Store.S_Name,
                                fc.Quantity,
                                fc.Warning,
                                fc.Store.Unit
                            };
                storeTempQuery = from fc in context.StoreTemps
                                 select fc;
                break;
            }
            
            grvStoreTemp.DataSource = storeTemp;
            grvStoreTemp.Columns[0].HeaderText = "Mã số";
            grvStoreTemp.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            grvStoreTemp.Columns[1].HeaderText = "Tên sản phẩm";
            grvStoreTemp.Columns[2].HeaderText = "Số lượng";
            grvStoreTemp.Columns[3].HeaderText = "Cảnh báo";
            grvStoreTemp.Columns[4].HeaderText = "Đơn vị";
            xuấtHàngRaTừKhoChínhToolStripMenuItem.Enabled = false;
            try
            {
                grvStoreTemp.CurrentCell = grvStoreTemp[0, grvStoreTempIndex];
            }
            catch (Exception)
            {
            }   
        }

        private void SelectStoreLog(Boolean type)
        {
            var WareHouse = from fc in context.Store_Logs
                            where fc.TypeIE == type
                            select new
                            { 
            fc.ID,
            fc.Store.S_Name,
            fc.TransferDate,
            fc.Quantity,
            fc.Price,
            };

            if (type)
            {
                wareHouse = from fc in context.Store_Logs where fc.TypeIE == type select fc;
                double totalMoney = 0;
                int quantity = 0;
                foreach (Store_Log storeLog in wareHouse)
                {
                    totalMoney += Convert.ToDouble(storeLog.Price);
                    quantity += Convert.ToInt32(storeLog.Quantity);
                }
                dataGridView1.DataSource = WareHouse;
                label20.Text = quantity.ToString() + "           ";
                label12.Text = totalMoney.ToString() + "           ";
                SetHeaderLogStoreImport();
            }
            else
            {
                wareHouseExport = from fc in context.Store_Logs where fc.TypeIE == type select fc;
                int quantity = 0;
                foreach (Store_Log storeLog in wareHouseExport)
                {
                    quantity += Convert.ToInt32(storeLog.Quantity);
                }
                dataGridView2.DataSource = WareHouse;
                label21.Text = quantity.ToString();
                SetHeaderLogStoreExport();
            }
        }

        private void SetHeaderLogStoreImport()
        {
            dataGridView1.Columns[0].HeaderText = "Mã số";
            dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dataGridView1.Columns[1].HeaderText = "Tên mặt hàng";
            dataGridView1.Columns[2].HeaderText = "Ngày thực hiện";
            dataGridView1.Columns[3].HeaderText = "Số lượng";
            dataGridView1.Columns[4].HeaderText = "Giá tiền";
        }

        private void SetHeaderLogStoreExport()
        {
            dataGridView2.Columns[0].HeaderText = "Mã số";
            dataGridView2.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dataGridView2.Columns[1].HeaderText = "Tên mặt hàng";
            dataGridView2.Columns[2].HeaderText = "Ngày thực hiện";
            dataGridView2.Columns[3].HeaderText = "Số lượng";
            dataGridView2.Columns[4].HeaderText = "Giá tiền";
        }


        private void InsertStockLog(Boolean type,int quantity,Decimal price)
        {
            Random random = new Random();
            var storeLog = new Store_Log {
            ID  = random.Next().ToString(),
            Price = price,
            Quantity = quantity,
            TransferDate = DateTime.Now,
            TypeIE = type,
            StoreID = lblIdStore.Text
            };
            context.Store_Logs.InsertOnSubmit(storeLog);
            context.SubmitChanges();
        }

        private void dgvWareHouse_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                string unit = dgvWareHouse.Rows[e.RowIndex].Cells[4].Value.ToString();
                lblIdStore.Text = dgvWareHouse.Rows[e.RowIndex].Cells[0].Value.ToString();
                lblNameProduct.Text = dgvWareHouse.Rows[e.RowIndex].Cells[1].Value.ToString();
                label6.Text = dgvWareHouse.Rows[e.RowIndex].Cells[2].Value.ToString() + " "+unit;
                lblWarning.Text = dgvWareHouse.Rows[e.RowIndex].Cells[3].Value.ToString();
                toolStripButton1.Enabled = true;
                toolStripButton2.Enabled = true;
                nhậpNhàngToolStripMenuItem.Enabled = true;
                xuấtHàngToolStripMenuItem.Enabled = true;
                dgvWareHouseIndex = e.RowIndex;
            }
            catch (Exception)
            { }
        }

        private void button3_Click(object sender, EventArgs e)
        {
           
        }

        public void Update()
        {
            SelectWareHouse("all");
            SelectStoreTemp("all");
            SelectStoreLog(true);
            SelectStoreLog(false);
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            Export();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            Import();
        }

        private void Import()
        {
            Store store = context.Stores.SingleOrDefault(x => x.ID == lblIdStore.Text);
            ImportStore export = new ImportStore(store);
            export.ShowDialog();
        }

        private void Export()
        {
            Store store = context.Stores.SingleOrDefault(x => x.ID == lblIdStore.Text);
            ExportStore export = new ExportStore(store);
            export.ShowDialog();
        }

        private void toolStripBtnAddToStore_Click(object sender, EventArgs e)
        {
            AddToStore();
        }

        private static void AddToStore()
        {
            AddToStore addToStore = new AddToStore();
            addToStore.ShowDialog();
        }

        private void thêmVàoKhoHàngToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddToStore();
        }

        private void nhậpNhàngToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Import();
        }

        private void xuấtHàngToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Export();
        }

        private void grvStoreTemp_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                string unit = grvStoreTemp.Rows[e.RowIndex].Cells[4].Value.ToString();
                lblIdStoreTemp.Text = grvStoreTemp.Rows[e.RowIndex].Cells[0].Value.ToString();
                lblNameStoreTemp.Text = grvStoreTemp.Rows[e.RowIndex].Cells[1].Value.ToString();
                lblQuantityStoreTemp.Text = grvStoreTemp.Rows[e.RowIndex].Cells[2].Value.ToString() + " " + unit;
                lblWarningStoreTemp.Text = grvStoreTemp.Rows[e.RowIndex].Cells[3].Value.ToString();
                xuấtHàngRaTừKhoChínhToolStripMenuItem.Enabled = true;
                grvStoreTempIndex = e.RowIndex;
            }
            catch (Exception)
            { 
            }
        }

        private void xuấtHàngRaTừKhoChínhToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ExportFromStoreMain();
        }

        private void ExportFromStoreMain()
        {
            StoreTemp storeTemp = context.StoreTemps.SingleOrDefault(x => x.StoID == lblIdStoreTemp.Text);
            DialogStoreMain dialogStoreMain = new DialogStoreMain(storeTemp);
            dialogStoreMain.ShowDialog();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

            int month = DateTime.Now.Month;
            int year = DateTime.Now.Year;
            DateTime dateFrom = new DateTime(year, month, 1);
            DateTime dateTo = DateTo(month, year);
            if (comboBox1.SelectedIndex == 0)
            {
                dateFrom = DateTime.Now.AddDays(-1);
                dateTo = DateTime.Now;
            }
            if (comboBox1.SelectedIndex == 1)
            {
                dateFrom = new DateTime(year, month, 1);
                dateTo = DateTo(month, year);
            }
            if (comboBox1.SelectedIndex == 2)
            {
                dateFrom = new DateTime(year, 1, 1);
                dateTo = DateTo(12, year);
            }

            SearchByDate(dateFrom, dateTo,"",true);
        }

        private void SearchByDate(DateTime dateFrom, DateTime dateTo,String keyWord,Boolean type)
        {
            if (!keyWord.Equals(""))
            {
                var WareHouse = from fc in context.Store_Logs
                                where fc.TransferDate >= dateFrom && fc.TransferDate <= dateTo && fc.TypeIE == type && fc.Store.S_Name.Contains(keyWord)
                                select new
                                {
                                    fc.ID,
                                    fc.Store.S_Name,
                                    fc.TransferDate,
                                    fc.Quantity,
                                    fc.Price
                                };
                wareHouse = from fc in context.Store_Logs
                            where fc.TransferDate >= dateFrom && fc.TransferDate <= dateTo && fc.TypeIE == type && fc.Store.S_Name.Contains(keyWord)
                            select fc;
                if (type)
                {
                    dataGridView1.DataSource = WareHouse;
                    SetHeaderLogStoreImport();
                }
                else
                {
                    dataGridView2.DataSource = WareHouse;
                    wareHouseExport = wareHouse;
                    SetHeaderLogStoreExport();
                }
              
            }
            else
            {
                var WareHouse = from fc in context.Store_Logs
                                where fc.TransferDate >= dateFrom && fc.TransferDate <= dateTo && fc.TypeIE == type
                                select new
                                {
                                    fc.ID,
                                    fc.Store.S_Name,
                                    fc.TransferDate,
                                    fc.Quantity,
                                    fc.Price
                                };
                wareHouse = from fc in context.Store_Logs
                            where fc.TransferDate >= dateFrom && fc.TransferDate <= dateTo && fc.TypeIE == type
                            select fc;
                if (type)
                {
                    dataGridView1.DataSource = WareHouse;
                    SetHeaderLogStoreImport();
                }
                else
                {
                    dataGridView2.DataSource = WareHouse;
                    SetHeaderLogStoreExport();
                    wareHouseExport = wareHouse;
                }

            }

            double totalMoney = 0;
            int quantity = 0;
            foreach (Store_Log storeLog in wareHouse)
            {
                totalMoney += Convert.ToDouble(storeLog.Price);
                quantity += Convert.ToInt32(storeLog.Quantity);
            }
            if (type)
            {
                label20.Text = quantity.ToString() + "           ";
                label12.Text = totalMoney.ToString() + "           ";
            }
            else
            {
                label21.Text = quantity.ToString();
            }
        }

        public DateTime DateTo(int month, int year)
        {
            DateTime dateTo = DateTime.Now;
            try
            {
                dateTo = new DateTime(year, month, 31);
            }
            catch (Exception)
            {
                try
                {
                    dateTo = new DateTime(year, month, 30);
                }
                catch (Exception)
                {
                    try
                    {
                        dateTo = new DateTime(year, month, 29);
                    }
                    catch (Exception)
                    {
                        dateTo = new DateTime(year, month, 28);
                    }
                }
            }

            return dateTo;
        }

        private void btnStock_Click(object sender, EventArgs e)
        {
            new ReportImport(wareHouse).Show();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            new ReportImport(wareHouseExport).Show();
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            int month = DateTime.Now.Month;
            int year = DateTime.Now.Year;
            DateTime dateFrom = new DateTime(year, month, 1);
            DateTime dateTo = DateTo(month, year);
            if (comboBox2.SelectedIndex == 0)
            {
                dateFrom = DateTime.Now.AddDays(-1);
                dateTo = DateTime.Now;
            }
            if (comboBox2.SelectedIndex == 1)
            {
                dateFrom = new DateTime(year, month, 1);
                dateTo = DateTo(month, year);
            }
            if (comboBox2.SelectedIndex == 2)
            {
                dateFrom = new DateTime(year, 1, 1);
                dateTo = DateTo(12, year);
            }

            SearchByDate(dateFrom, dateTo, "", false);

            
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            ExportFromStoreMain();
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            SelectWareHouse("thieu");
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            SelectWareHouse("du");
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            SelectWareHouse("all");
        }

        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            SelectStoreTemp("thieu");
        }

        private void toolStripButton9_Click(object sender, EventArgs e)
        {
            SelectStoreTemp("du");
        }

        private void toolStripButton10_Click(object sender, EventArgs e)
        {
            SelectStoreTemp("all");
        }

        private void hiểnThịSảnPhẩmThiếuToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SelectWareHouse("thieu");
        }

        private void hiểnThịSảnPhẩmĐủToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SelectWareHouse("du");
        }

        private void hiểnThịTấtCảToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SelectWareHouse("all");
        }

        private void hiểnThịSảnPhẩmĐủToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            SelectStoreTemp("du");
        }

        private void hiểnThịSảnPhẩmThiếuToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            SelectStoreTemp("thieu");
        }

        private void hiểnThịTấtCảSảnPhẩmToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SelectStoreTemp("all");
        }

        private void toolStripButton11_Click(object sender, EventArgs e)
        {
            new ReportStoreTemp(storeTempQuery).Show();
        }

        private void toolStripButton12_Click(object sender, EventArgs e)
        {
            new ReportStore(wareHouseQuery).Show();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SearchByDate(dateTimePicker2.Value, dateTimePicker1.Value, textBox1.Text,false);
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            SearchByDate(dtpFrom.Value, dtpTo.Value, txtSearchName.Text,true);
        }

        private void tbpImportExport_Click(object sender, EventArgs e)
        {

        }

        private void newToolStripButton1_Click(object sender, EventArgs e)
        {
            new ReportImport(wareHouse).Show();
        }

        private void btnSearchTemp_Click(object sender, EventArgs e)
        {
            searchStockTempByName(txtSearchTemp.Text);
        }

        public void searchStockTempByName(String name)
        {
             var storeTemp = from fc in context.StoreTemps where fc.Store.S_Name.Contains(name)
                            select new
                            {
                                fc.Store.ID,
                                fc.Store.S_Name,
                                fc.Quantity,
                                fc.Warning,
                                fc.Store.Unit
                            };
             storeTempQuery = from fc in context.StoreTemps
                              where fc.Store.S_Name.Contains(name)
                                 select fc;

            grvStoreTemp.DataSource = storeTemp;
            grvStoreTemp.Columns[0].HeaderText = "Mã số";
            grvStoreTemp.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            grvStoreTemp.Columns[1].HeaderText = "Tên sản phẩm";
            grvStoreTemp.Columns[2].HeaderText = "Số lượng";
            grvStoreTemp.Columns[3].HeaderText = "Cảnh báo";
            grvStoreTemp.Columns[4].HeaderText = "Đơn vị";
            xuấtHàngRaTừKhoChínhToolStripMenuItem.Enabled = false;
            try
            {
                grvStoreTemp.CurrentCell = grvStoreTemp[0, grvStoreTempIndex];
            }
            catch (Exception)
            {
            }   
        }

        private void btnSearchStock_Click(object sender, EventArgs e)
        {
            searchStockByName(txtSearchStock.Text);
        }

        private void searchStockByName(String name)
        {
            wareHouseQuery = from fc in context.Stores where fc.S_Name.Contains(name) select fc;
            dgvWareHouse.DataSource = wareHouseQuery;
            dgvWareHouse.Columns[0].HeaderText = "Mã số";
            dgvWareHouse.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            dgvWareHouse.Columns[1].HeaderText = "Tên sản phẩm";
            dgvWareHouse.Columns[2].HeaderText = "Số lượng";
            dgvWareHouse.Columns[3].HeaderText = "Cảnh báo";
            dgvWareHouse.Columns[4].HeaderText = "Đơn vị";
            dgvWareHouse.Columns[5].HeaderText = "Số lượng tiêu chuẩn";
        }

        public void SetInforAdmin(Admin admin)
        {
            this.admin = admin;
        }
    }
}
